package org.water.base.support;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.water.base.repository.BaseRepository;

/**
 * 
 * @author qzy
 *
 */
class SimpleBaseRespositoryFactory<M, ID extends Serializable> extends JpaRepositoryFactory {

	private final EntityManager entityManager;
	private static Logger logger=LogManager.getLogger(SimpleBaseRespositoryFactory.class);
	public SimpleBaseRespositoryFactory(EntityManager entityManager) {
		super(entityManager);
		this.entityManager=entityManager;
	}
	protected Object getTargetRepository(RepositoryMetadata metadata) {
	    Class<?> repositoryInterface = metadata.getRepositoryInterface();
	    if (isBaseRepository(repositoryInterface))
	    {
			Class<?> domainType=metadata.getDomainType();
			logger.debug("entity:"+domainType);
	    	JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(domainType);
			SimpleBaseRepository repository = new SimpleBaseRepository((JpaEntityInformation) entityInformation, this.entityManager);
	        return repository;
	    }
	    return super.getTargetRepository((RepositoryInformation) metadata);
	  }
	  @Override
	  protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
	    if (isBaseRepository(metadata.getRepositoryInterface())) {
	      return SimpleBaseRepository.class;
	    }
	    return super.getRepositoryBaseClass(metadata);
	  }

	  private boolean isBaseRepository(Class<?> repositoryInterface) {
	    return BaseRepository.class.isAssignableFrom(repositoryInterface);
	  }
}
